import openpyxl
from io import BytesIO
import os
import pandas as pd
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter


def export_to_xls(data: list) -> BytesIO:
    """Экспорт в Excel."""
    wb = openpyxl.Workbook()
    ws = wb.active

    headers = ["ID", "Name", "Email"]
    for col_num, header in enumerate(headers, start=1):
        col_letter = openpyxl.utils.get_column_letter(col_num)
        ws[f"{col_letter}1"] = header

    for row_num, user in enumerate(data, start=2):
        ws.cell(row=row_num, column=1, value=user.id)
        ws.cell(row=row_num, column=2, value=user.name)
        ws.cell(row=row_num, column=3, value=user.email)

    return BytesIO(wb.read())


def export_to_csv(data: list) -> bytes:
    """Экспорт в CSV."""
    df = pd.DataFrame([el.to_dict() for el in data])
    csv_buffer = BytesIO()
    df.to_csv(csv_buffer, index=False)
    return csv_buffer.getvalue()


def export_to_pdf(data: list) -> bytes:
    """Экспорт в PDF."""
    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=letter)
    c.setFont("Helvetica", 10)

    # Заголовок таблицы
    c.drawString(50, 750, "ID\tName\tEmail")

    # Данные пользователей
    for i, user in enumerate(data, start=1):
        c.drawString(50, 740 - (i * 20), f"{user.id}\t{user.name}\t{user.email}")

    c.save()
    return buffer.getvalue()


def save_csv_from_buffer(csv_data: bytes, file_path: str):
    """
    Сохраняет данные из CSV буфера в файл.

    :param csv_data: Байтовые данные CSV.
    :param file_path: Путь к файлу, в который будут сохранены данные.
    """
    if not os.path.exists(os.path.dirname(file_path)):
        os.makedirs(os.path.dirname(file_path))

    with open(file_path, 'wb') as file:
        file.write(csv_data)